import java.util.*;
import java.io.IOException;
import java.net.*;

public class DiscAEClient extends Thread{
	
	private DatagramSocket dClientSock;
	
	public static final int CLIENT_PORT = 56792;
	private ArrayList<String> knownPeers;
	
	// SWITCH TO STATIC LATER
	private String ID;
	private int version;
	
	
	public DiscAEClient(String UUID, int v){
		knownPeers = new ArrayList<String>();
		version = v;
		ID = UUID;
			
		try {
			dClientSock = new DatagramSocket(CLIENT_PORT);
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void run(){
		while (true){
			try {
				
				// DISCOVERY CLIENT STUFF HERE
				// START BY SENDING OUT A REQUEST
				dClientSock = new DatagramSocket(CLIENT_PORT);
				String output = "";
				output += "MessageType:AE_REQUEST\n";
				output += "SourceUUID:" + ID + "\n";
				output += "ProtocolVersion:" + version + "\n";
				output += "EndOfMessage";
				
				byte[] buffer = output.getBytes();
				DatagramPacket discPkt = new DatagramPacket(buffer, buffer.length);
				InetAddress discAddr = InetAddress.getByName("255.255.255.255");
				
				discPkt.setAddress(discAddr);
				dClientSock.send(discPkt);
				
				// set a timeout for the socket - we want to wait for a packet now
				// wait until we receive some packet
				dClientSock.setSoTimeout(1000);
				byte[] discIncoming = new byte[DiscoveryServer.MAX_PACKET_SIZE];
				DatagramPacket discInc = new DatagramPacket(discIncoming, discIncoming.length);
				dClientSock.receive(discInc);
				
				// parse out whatever we got from the server
				// add all the peers to our list
				String incomingDiscData = new String(discInc.getData());
				if (incomingDiscData.contains("KnownPeers:")){
					int start = incomingDiscData.lastIndexOf("KnownPeers:");
					int end = incomingDiscData.indexOf("\n", start);
					int addrLen = "KnownPeers:".length();
					String peers = incomingDiscData.substring(start+addrLen, end);
					String[] peerArray = peers.split("\\|");
					for (String str : peerArray){
						if (!knownPeers.contains(str))
							knownPeers.add(str);
					}
					
					
				}
				
			} catch (SocketTimeoutException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}catch (SocketException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (UnknownHostException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	
}
